<template>
    <el-upload class="upload-demo" ref="upload" action="/api/document/index-document" :on-preview="handlePreview"
        :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :on-change="changeUpload"
        :on-success="handleSuccess" :on-error="handleError">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上 传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传 {{ fileType.join('，') }} 文件，且不超过{{ fileSize }}MB</div>
    </el-upload>
</template>

<script>
import axios from 'axios';

export default {
    props: {
        // 文件类型
        fileType: {
            type: Array,
            default: () => [],
        },
        // 文件大小，单位MB
        fileSize: {
            type: Number,
            default: 10,
        }
    },
    data() {
        return {
            fileList: []
        };
    },
    beforeCreate() {
        this.$nextTick(() => {
            this.fetchFileList();
        })
    },
    methods: {
        uuid() {
            const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
            return `${s4()}${s4()}${s4()}`
        },
        // 更新文件列表数据
        async fetchFileList() {
            try {
                const response = await axios.get('/api/document/list');
                this.fileList = (response.data || []).map(item => {
                    return {
                        name: item,
                        status: "success",
                        uid: this.uuid(),
                        url: ''
                    }
                });
            } catch (error) { }
        },
        changeUpload(file, fileList) {
            let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            let fileType = this.fileType.map(it => it.toUpperCase());
            if (fileType.length && !fileType.includes(testmsg.toUpperCase())) {
                this.$message.error(
                    this.fileType.length
                        ? `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
                        : "请上传图片或者视频"
                );
                fileList.splice(fileList.length - 1, 1);
                return false;
            }
            if (this.fileSize) {
                const isLt = file.size / 1024 / 1024 < this.fileSize;
                if (!isLt) {
                    this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
                    fileList.splice(fileList.length - 1, 1);
                    return false;
                }
            }
            return true;
        },
        submitUpload() {
            this.$refs.upload.submit();
        },
        async handleRemove(file, fileList) {
            if (file.raw) return;// 删除未上传的内容，不执行后台删除操作
            try {
                await axios.delete(`/api/document/${file.name}`);
            } catch (error) { }
        },
        handlePreview(file) { },
        handleSuccess(response, file, fileList) {
            this.$message.success("上传成功");
        },
        handleError(err, file, fileList) {
            this.$message.success("上传失败，请刷新重试");
        },
    }
}
</script>